﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YuQueSdk.Dto;

namespace YuQueSdk
{
    /// <summary>
    /// 用于支持async/await模型
    /// </summary>
    public partial class YuQueClient
    {
        /// <summary>
        /// 获取单篇文档的详细信息
        /// </summary>
        /// <param name="docRepo">文档所属的知识库 如：https://www.yuque.com/yuque/developer/repo 中的【yuque/developer】</param>
        /// <param name="slug">文档的路径 如：https://www.yuque.com/yuque/developer/repo 中的【repo】</param>
        /// <returns>文档的详细信息</returns>
        public async Task<DocDetail> GetDocDetailAsync(string docRepo, string slug)
        {
            string jsonStr = await HttpHelper.HttpGetAsync($"{baseUrl}repos/{docRepo}/docs/{slug}", _token, _userAgent);
            return JsonConvert.DeserializeObject<DocDetail>(jsonStr);
        }

        /// <summary>
        /// 获取知识库下的目录
        /// </summary>
        /// <param name="docRepo">文档所属的知识库 如：https://www.yuque.com/yuque/developer/repo 中的【yuque/developer】</param>
        /// <returns>目录信息</returns>
        public async Task<List<Topic>> GetRepoTopicAsync(string docRepo)
        {
            string jsonStr = await HttpHelper.HttpGetAsync($"{baseUrl}repos/{docRepo}/toc", _token, _userAgent);
            return JsonConvert.DeserializeObject<TopicInfo>(jsonStr).Data;
        }

        /// <summary>
        /// 获取知识库下的目录（树结构）
        /// </summary>
        /// <param name="docRepo">文档所属的知识库 如：https://www.yuque.com/yuque/developer/repo 中的【yuque/developer】</param>
        /// <returns>目录信息</returns>
        public async Task<List<TopicTree>> GetRepoTopicTreeAsync(string docRepo)
        {
            string jsonStr = await HttpHelper.HttpGetAsync($"{baseUrl}repos/{docRepo}/toc", _token, _userAgent);
            List<Topic> topicList = JsonConvert.DeserializeObject<TopicInfo>(jsonStr).Data;
            List<TopicTree> result = new List<TopicTree>();
            var firstList = topicList.Where(x => x.Level == 0);//第一级
            return ProcessTree(firstList, topicList);
        }
    }
}
